<?php
//teste
class AuthController extends BaseController {
    
    public function loginAction() {
        $this->_helper->layout()->setLayout('login');
        $form = new Form_Auth_Login();
        $this->view->form = $form;        
    }
    
    public function logoutAction() {
        Zend_Auth::getInstance()->clearIdentity();
        $this->_helper->redirector('login');
    }

    public function authenticateAction(){
        try {
            $login = $this->_getParam('login');
            $password = $this->_getParam('senha');
            
            $db = Zend_Db_Table::getDefaultAdapter();
            $authAdapter = new Zend_Auth_Adapter_DbTable($db, 'pagservice.usuarios', 
                    'login', 'senha', 'MD5(?)');
            $authAdapter->setIdentity($login)->setCredential($password);

            $authReturn = Zend_Auth::getInstance()->authenticate($authAdapter);
            
//            var_dump($authReturn); die;

            if (!$authReturn->isValid()) {
                throw new Exception('Login e/ou senha inválidos.');
            }

            $model = new Application_Model_Usuario();
            $usuario = $model->fetchRow("login = '$login'");
            
            /* Grava o objeto na sessao */
            Zend_Auth::getInstance()->getStorage()->write($usuario);
            
            $this->_helper->redirector('index', 'index');
            
        } catch (Exception $exc) {
             $this->_helper->redirector('login');
        }

        
    }
    
}
